package problem106;

//106. 从后序和中序遍历序列构造二叉树
//https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

class Solution {
    int postIndex = 0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = inorder.length-1;
        return buildTreeChild(inorder, postorder, 0, inorder.length-1);
    }
    public TreeNode buildTreeChild(int[] inorder, int[] postorder, int begin, int end) {
        if(begin > end) return null;
        TreeNode root = new TreeNode(postorder[postIndex]);
        int index = findIndex(inorder, postorder[postIndex], begin, end);
        postIndex--;
        root.right = buildTreeChild(inorder, postorder, index+1, end);
        root.left = buildTreeChild(inorder, postorder, begin, index-1);
        return root;
    }

    public int findIndex(int[] inorder, int target, int begin, int end) {
        for(int i = begin; i<=end; i++) {
            if(inorder[i] == target) {
                return i;
            }
        }
        return -1;
    }
}